package ycl.important.service.impl.sys;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ycl.important.common.base.service.impl.BaseServiceImpl;
import ycl.important.entity.sys.UserFriends;
import ycl.important.mapper.sys.UserFriendsMapper;
import ycl.important.service.sys.UserFriendsService;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 用户的朋友 服务实现类
 * </p>
 *
 * @author YCL
 * @since 2021-06-15
 */
@Service("userFriendsService")
public class UserFriendsServiceImpl
		extends BaseServiceImpl<UserFriendsMapper, UserFriends>
		implements UserFriendsService {

	@Resource
	private UserFriendsMapper userFriendsMapper;

	@Override
	public Map<Long, Set<Long>> selectByUserIds(Set<Long> userIds) {
		LambdaQueryWrapper<UserFriends> wrapper = new LambdaQueryWrapper<>();
		wrapper.in(UserFriends::getUserId, userIds);
		List<UserFriends> list = userFriendsMapper.selectList(wrapper);

		Map<Long, Set<Long>> map = new HashMap<>();
		list.forEach(v -> {
			Long userId = v.getUserId();

			Set<Long> friendIds = map.get(userId);
			if (CollUtil.isEmpty(friendIds)) {
				friendIds = new HashSet<>();
			}
			friendIds.add(v.getFriendId());
			map.put(userId, friendIds);
		});
		return map;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addFriends(List<Long> userIds) {
		if (CollUtil.isEmpty(userIds) || userIds.size() <= 1)
			return;

		Set<Long> ids = new HashSet<>(userIds);
		Set<UserFriends> list = new HashSet<>();
		for (Long userId : ids) {
			for (Long friendId : ids) {
				if (friendId.equals(userId)) continue;

				boolean b = userFriendsMapper.selectExistByUserIdFriendId(userId, friendId);
				if (b) continue;

				UserFriends e = new UserFriends();
				e.setUserId(userId);
				e.setFriendId(friendId);
				list.add(e);
			}
		}

		if (CollUtil.isNotEmpty(list))
			saveBatch(list);
	}
}
